package cn.edu.lcu.cs.javaweb.web;

import java.io.IOException;
import java.time.Instant;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Ling
 *         <li>用注解的方式配置Servlet，及演示Servlet生命周期</li>
 *         <li>Servlet是单例模式，服务器内存里只有一个实例</li>
 *
 */
@WebServlet({ "/life-demo", "/life" }) // 可用字符串数组常量配置多个地址映射
//@WebServlet({ "/life-demo" }) 
//@WebServlet("/life-demo") // 如果只有一个地址映射，可直接用单个字符串进行映射
public class LifeDemoServlet extends HttpServlet {

	/**
	 * Servlet只被实例化一次
	 */
	public LifeDemoServlet() {
		// 控制台上输出什么时间，被实例化
		System.out.println(Instant.now() + "\tLifeCycleServlet被实例化了");
	}

	/**
	 * Servlet只初始化一次
	 */
	public void init(ServletConfig config) throws ServletException {
		System.out.println(Instant.now() + "\tLifeCycleServlet.init()被调用了");
	}

	/**
	 * 每次访问此Servlet，都会被执行。它根据http method的不同，分别调用不同的方法。如 get post delete put 等等
	 */
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println(Instant.now() + "\tLifeCycleServlet.service()被调用了");
		super.service(req, resp);
	}

	/**
	 * 最多执行一次。如果服务器被强制关闭，此方法也可能来不及执行
	 */
	public void destroy() {
		System.out.println(Instant.now() + "\tLifeCycleServlet.destroy()被调用了");
	}

	/**
	 * 被service方法调用
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println(Instant.now() + "\tLifeCycleServlet.doGet()被调用了");
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * 被service方法调用
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		System.out.println(Instant.now() + "\tLifeCycleServlet.doPost()被调用了");
		doGet(request, response);
	}

}
